<template>
	<div>
		<div class="popbg" @click="close"></div>
		<div class="pop_box orderBox">
			<div class="memberBox">
				<div class="memberList">
					<img class="memberItem" v-for="(item,index) in users" :key="index" :src="item.headImg" />
				</div>
				<div class="clearBtn" @click="clearBtn"><i class="clearIcon"></i>清空已选</div>
			</div>
			<div class="classifyList">
				<div class="filterList padTB40" v-for="item in shoppingList" :key="guid(item)">
					<!-- <img :src="baseURL + item.mainImageUrl" mode="aspectFill" class="photo"> -->
					<imageCom :src="baseURL + item.mainImageUrl" class="photo"></imageCom>
					<div class="marL40 filterItem">
						<div class="font28 bold line15">{{item.productName}}</div>
						<div class="font24 line15 itemspan" >{{ buildDesc(item) }}</div>
						<div class="addSubtWrapper">
							<div class="total bold font38">
								¥ {{ singleItemCalculate(item) }}
							</div>
							<div class="addSubt">
								<span class="operate" v-show="item.qty > 0" @click="decreaseFn(item)">-</span>
								<span class="much" v-show="item.qty > 0">{{item.qty}}</span>
								<span class="operate" @click="increaseFn(item)">+</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { mapState, mapGetters,mapMutations } from 'vuex'
import { baseURL } from '@/api/config'
import { singleItemCalculate } from "@/utils/cartFn";
import {ClearCart} from '@/api/order'
import imageCom from "@/components/common/imageCom.vue";

export default {
  name: 'productList',
  components: {
    imageCom
  },
  props: {
    users: {
      type: Array,
      default:function(){
        return []
      }
    }
  },
  computed:{
    ...mapState({
      shoppingList: (state) => state.cartModule.shoppingList,
    }),
    ...mapGetters({
      mapShoppingList: 'mapShoppingList',
    }),
  },
  data(){
    return {
      baseURL
    }
  },
  methods:{
    close(){
      this.$store.commit('showDetail', false)
    },
    itemQty(item){
      let qty = 0;
      for (let i of this.shoppingList) {
        if (i.productId == item.productId) {
          qty++;
        }
      }
      return qty;
    },
    // -------------------------商品列表操作-------------------------------
      ...mapMutations([
        "increaseProCart",
        "decreaseProCart",
        "setShoppintList",
        "clearshoppingList",
        "modifyProNew",
      ]),
    decreaseFn(item){
      //this.decreaseProCart({ item: item })
      this.$store.dispatch('decreaseProCart',{ item: item });
    },
    increaseFn(item){
      //this.increaseProCart({ item: item })
      this.$store.dispatch('increaseProCart',{ item: item });
    },
    /**
     * @description 清空按钮
     */
    async clearBtn() {
      let params = {
        // memberId: "string",
        // peopleCount: 0,
        // comment: "string",
        tableId: this.$store.state.tableInfo.tableId,
        //items: this.shoppingList
      }
      let {returnData = false} = await ClearCart(params)
      if(returnData == false) return
      console.log(returnData)
      this.clearshoppingList()
    },
    /**
     * @description 删除按钮
     */
    delBtn(item) {
      if (!item.isSlide || item.isSlide == false) return;
      //let that = this;
    //   uni.showModal({
    //     title: "提示",
    //     content: "是否删除该商品",
    //     success: function (res) {
    //       if (res.confirm) {
    //         let res = that.shoppingList.filter((s) => {
    //           return s != item;
    //         });
    //         that.setShoppintList({ list: res });
    //       }
    //     },
    //   });
    },
    /**
     * @description 编辑按钮
     */
    modifyBtn(item) {
      if (!item.isSlide || item.isSlide == false) return;
      let types = [3, 5];
      let params = {};
      if (!types.includes(item.type)) {
        params = {
          item,
          cb: this.singleModalCallBack,
        };
      } else {
        params = {
          needReq: false,
          item,
          isModify: true,
          popType: 3, //菜品用到
          cb: this.modifyCallBack,
        };
      }
      setTimeout(() => {
        this.$set(item, "isSlide", false);
        return params//uni.$emit("modifyBtn", params);
      }, 0);
    },
    /**
     * @description 菜品/套餐回调
     */
    modifyCallBack(params) {
      let { item, mapItem } = params;
      this.modifyProNew({ cur: item, replace: mapItem });
    },
    /**
     * @description 普通商品回调
     */
    singleModalCallBack(params) {
      let { count, item } = params;
      let arr = this.shoppingList.filter((s) => s.productId != item.productId);
      let firstIdx = this.shoppingList.findIndex(
        (s) => s.productId == item.productId
      );
      let subArr = [];
      for (let i = 0; i < count; i++) {
        subArr.push({ ...item });
      }
      arr.splice(firstIdx, 0, ...subArr);
      this.setShoppintList({ list: arr });
    },
    // -------------------------template显示-------------------------------
    /**
     * @description 展开/关闭 子选项编辑
     */
    callSlide(item) {
      if (!item.isSlide) {
        // item.isSlide = true;
        this.$set(item, "isSlide", true);
      } else {
        let val = !item.isSlide;
        this.$set(item, "isSlide", val);
      }
    },
    /**
     * @description 计算单一产品的价格
     */
    singleItemCalculate,
    /**
     * @description 生成独一无二key，避免套餐删除时，同一productId套餐出现编辑状态
     */
    guid() {
      let genStr = () => {
        let str = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
          /[xy]/g,
          function (c) {
            var r = (Math.random() * 16) | 0,
              v = c == "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
          }
        );
        return str;
      };
      let uid = genStr();
      return uid;
    },
    /**
     * @description 描述
     */
    buildDesc(item) {
      let str = "";
      let { type } = item;
      if (type == 3) {
        if (item.packages.length == 0) return str;
        let arr = [];
        for (let sitem of item.packages) {
          arr.push(`${sitem.productName}x${sitem.qty}`);
          // for (let ssitem of sitem.items) {
          //   ssitem.itemCount > 0 &&
          //     arr.push(`${ssitem.productName}x${ssitem.itemCount}`);
          // }
        }
        str = arr.join("+");
      } else if (type == 5) {
        if (item.foodGroups.length == 0) return str;
        let arr = [];
        item.foodGroups.forEach((sitem) => {
          // sitem.items.forEach((ssitem) => {
          //   ssitem.isDefault == true && arr.push(`${ssitem.itemTitle}`);
          // });
          arr.push(`${sitem.itemTitle}`);
        });
        str = arr.join("+");
      } else {
        str = item.model;
      }
      return str;
    },
    /**
     * @description 单位
     */
    getUnit(item) {
      let unitName = "";
      switch (item.type) {
        case 3:
          unitName = item.baseUnit.unitName;
          break;
        case 5:
          unitName = item.baseUnit.unitName;
          break;
        default:
          unitName = item.unitName;
      }
      return unitName;
    },
    // -------------------------初始请求-----------------------------
    /**
     * @description 订单详情
     */
    // async reqGetOrderByTableId() {
    //   let { returnData = false, isSuccess } = await GetOrderByTableId({
    //     tableId: this.tableId,
    //   });
    //   if (isSuccess == false) {
    //     this.tableObject = this.$store.state.ctrl.tableObject;
    //     this.setShoppintList({ list: [] });
    //     return;
    //   }
    //   this.order = returnData;
    //   this.tableObject = returnData.table;
    //   this.setShoppintList({ list: [] });
    // },
    // -------------------------处理请求数据-----------------------------
    handleItem(item, isPackage = false) {
      if (isPackage == true) {
        let res = item.itemCount > 0 ? true : false;
        if (res == false) return res;
      }
      let unitId = "";
      if (item.type == 3 || item.type == 5) {
        unitId = isPackage == false ? item.baseUnit.unitId : item.unit.unitId;
      } else {
        unitId = item.baseUnitId ?? "";
      }
      let obj = {
        productId: item.productId,
        unitId,
        qty: item?.isWeightingSale == true ? 0 : 1,
        state: item.type,
        configIds: [],
        items: [],
        comment: "",
      };
      // 备注
      if (item.comment) {
        obj.comment = item.comment;
      }
      if (item.type == 3 && isPackage == false) {
        for (let pitem of item.packages) {
          if (pitem.items.lenght <= 0) continue;
          pitem.items.forEach((pi) => {
            let res = this.handleItem(pi, true);
            if (res != false) {
              obj.items.push(res);
            }
          });
        }
      } else if (item.type == 5) {
        for (let fitem of item.foodGroups) {
          for (let i of fitem.items) {
            if (i.isDefault == true) {
              obj.configIds.push(i.itemId);
            }
          }
        }
      }
      return obj;
    },
    handleData() {
      let arr = [];
      this.shoppingList.forEach((sitem) => {
        arr.push(this.handleItem(sitem));
      });
      return arr;
    },
    // ----------------------------下单-----------------------------
    addOrderBtn() {
      if (this.order.orderId) {
        this.reqAddFoodItem();
      } else {
        this.reqAddOrder();
      }
    },
    /**
     * @description 下单
     */
    // async reqAddOrder() {
    //   if (this.shoppingList.length == 0) return;
    //   this.loading = true;
    //   let tableId = this.tableId ?? this.tableObject.tableId;
    //   let items = this.handleData();
    //   let params = {
    //     tableId,
    //     memberId: "",
    //     // state: 0,
    //     items,
    //   };
    //   console.log(items);
    //   let { isSuccess, message } = await AddOrder(params);
    //   this.loading = false;
    //   if (isSuccess == false) {
    //     this.$refs.tips.openTips(message);
    //     return;
    //   } else if (isSuccess == true) {
    //     this.$store.commit("setMultipleVisible", {
    //       list: ["goodsRoomVisble", "placeOrderVisible"],
    //       show: true,
    //     });
    //   }
    // },
    /**
     * @description 加菜
     */
    // async reqAddFoodItem() {
    //   let params = {
    //     orderId: this.order.orderId,
    //     items: this.handleData(),
    //   };
    //   this.tt = params;
    //   let { isSuccess, message } = await AddFoodItem(params);
    //   if (isSuccess == false) {
    //     this.$refs.tips.openTips(message);
    //     return;
    //   } else if (isSuccess == true) {
    //     this.isSuccess = true;
    //   }
    // },
    toHome() {
      //uni.$emit("tabCtrl", 1);
      this.$store.commit("setMultipleVisible", {
        list: ["roomVisible"],
        show: true,
      });
    },
  }
}
</script>

<style lang="scss">
  .popbg,.pop_box{ z-index: -1;}
	// 点单
	.orderBox{ top: 20%; left:0; width: 100%; bottom: 0; border-radius: 0.5rem 0.5rem 0 0; text-align: left; padding: 0.75rem; transform: translate(0,0);box-sizing: border-box;
		.memberBox{ display: flex; justify-content: space-between; align-items: center; padding-bottom: 0.5rem;
			.memberList{ display: flex; align-items: center;
				.memberItem{ width: 1.5rem; height: 1.5rem; border-radius: 50%; margin-right: 0.2rem;}
			}
			.clearBtn{ position: relative; font-size: 0.7rem; padding-left: 1.2rem; color: #929292;
				.clearIcon{ position: absolute; left: 2.4%; top: 50%; display: block; margin-top: -0.4rem; width: 0.8rem; height: 0.8rem; background: url(~@/assets/clearIcon.png) no-repeat; background-size: contain;
				} 
			}
		}
		.classifyList{ height: calc(100% - 100px); overflow-y: scroll; flex: 1; -webkit-flex: 1; box-sizing: border-box;
		}
		.filterList{ position: relative; display: flex; display: -webkit-flex; flex-wrap: wrap; -webkit-flex-wrap: wrap;  align-content: flex-start; -webkit-align-content: flex-start;
			.photo{ display: block; text-align: center; overflow: hidden; width: 4.25rem;  height: 4.25rem; border-radius: 0.3rem;}
			.filterItem{ flex: 1; display: flex; flex-direction: column; justify-content: space-between;
			.itemspan{ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2;-webkit-box-orient: vertical;
				.num{ background-color: #ffeca9; color: #feb329; border-radius: 5px;padding: 0 0.25rem; margin-right: 0.25rem;}
			}
			}
			&:first-child{ padding-top: 0;}
			&+.filterList:after{content: " "; position: absolute; left: 0.4rem; top: 0; right: 0.4rem; height: 1px; border-top: 1px solid #E5E5E5; color: #E5E5E5; -webkit-transform-origin: 0 0; transform-origin: 0 0; -webkit-transform: scaleY(0.5); transform: scaleY(0.5);}
		}
		.addSubtWrapper{ display: flex; display: -webkit-flex; align-items: flex-end; -webkit-align-items: flex-end; justify-content: space-between; -webkit-justify-content: space-between;
			.total{ width: 4rem;}
			.addSubt{ width: 4rem; height: calc(1rem + 2px); display: flex; display: -webkit-flex; align-items: center; -webkit-align-items: center; font-size: 0.8rem; overflow: hidden; white-space: nowrap;}
			.operate{ width: 1rem; height: 1rem; line-height: 1rem;  text-align: center; cursor: pointer; color: #feb229; border: 1px solid $mainColor; border-radius: 4px;
				&:last-child{ border: 1px solid $mainColor; background-image: linear-gradient(to right,$mainColor,#ffae44); color: #fff;}
			}
			.much{ width: calc(100% - 2rem - 2px);  height: 1rem; line-height: 1rem;  text-align: center; outline: none; border: none; border-radius: 0;}
		}
	}
</style>
